package com.example.controller.pc;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.dto.pc.GetProductLineMachineHzViewDto;
import com.example.entity.dto.pc.GetTYByProductIdHzViewDto;
import com.example.entity.dto.pc.PPRDto;
import com.example.entity.dto.pc.PPRListDto;
import com.example.entity.hz.MOCTA;
import com.example.entity.mysql.Productprocessresource;
import com.example.entity.mysql.Resourcegroup;
import com.example.entity.vo.pc.GetProductLineMachineHzViewVo;
import com.example.entity.vo.pc.PPRListVo;
import com.example.entity.vo.pc.PPRVo;
import com.example.entity.vo.pc.PPRresourceVo;
import com.example.entity.yifei.Mocty;
import com.example.mapper.MoctaMapper;
import com.example.mapper.MoctyMapper;
import com.example.mapper.SFCTEMapper;
import com.example.mapper.pc.ProductprocessresourceMapper;
import com.example.mapper.pc.ScheduleMapper;
import com.example.service.pc.ProductprocessresourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.untils.BeanUtils;
import com.example.untils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-05-19
 */
@RestController
@Api(tags = "品号工序资源表")
@RequestMapping("/api/productprocessresource")
public class ProductprocessresourceController {

    @Autowired
    private ProductprocessresourceService service;
    @Autowired
    private ProductprocessresourceMapper mapper;
    @Autowired
    private ResourcegroupService resourcegroupService;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private SFCTEMapper sfcteMapper;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private MoctaMapper moctaMapper;

    @ApiOperation("原列表(宏竹版)")
    @PostMapping("PPRListHzVersion")
    public Result<PageInfo<List<PPRListVo>>> PPRListHzVersion(@RequestBody PPRListDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<PPRListVo> res = scheduleMapper.proProcessRoute(dto);
        PageInfo<List<PPRListVo>> pageInfo = new PageInfo(res);
        List<String> params = new ArrayList<>();
        // 把拿出来的数据复制到 PPRListVo
        for (PPRListVo t : res) {
            params.add(t.getInproductno().trim() + "-" + t.getProductId().trim() + "-" + t.getProcessRoute().trim()
                    + "-" + t.getProcessId().trim() + "-" + t.getInvrt_name().trim());
        }

        // 查询 品号-工艺-工序  一样的到Set
        List<PPRVo> set = mapper.getListHzVersion(params);
        Map<String, List<PPRresourceVo>> map = new HashMap<>();
        for (PPRVo p : set) {
            List<PPRresourceVo> list = map.get(p.getProductId().trim() + "-" + p.getInv_no().trim() + "-" + p.getProcessRoute().trim()
                    + "-" + p.getProcessId().trim() + "-" + p.getInvrt_name().trim());
            if(list == null) {
                list = new ArrayList<>();
            }
            PPRresourceVo t = new PPRresourceVo();
            BeanUtils.copyPropertiesIgnoreCase(p, t);
            list.add(t);
            map.put(p.getProductId().trim() + "-" + p.getInv_no().trim() + "-" + p.getProcessRoute().trim()
                    + "-" + p.getProcessId().trim() + "-" + p.getInvrt_name().trim(), list);
        }
        for (PPRListVo vo : res) {
//            String processName = vo.getProcessName();
            List<PPRresourceVo> vos = map.get(vo.getInproductno().trim() + "-" + vo.getProductId().trim() + "-" + vo.getProcessRoute().trim()
                    + "-" + vo.getProcessId().trim() + "-" + vo.getInvrt_name().trim());
            if (vos == null) continue;
            vo.setResourceGroups(vos);
//            vo.setProcessName(processName);
        }
        return Result.success(pageInfo);
    }

    @ApiOperation("原列表")
    @PostMapping("PPRList")
    public Result<PageInfo<List<PPRListVo>>> PPRList(@RequestBody PPRListDto dto) {
//        HashMap<String, Object> paramMap = new HashMap<>();
//        paramMap.put("orderNo", dto.getProductId());
//        String result3 = HttpUtil.get(UrlConstant.proProcessRoute, paramMap);
//        Result<List> result = JSONUtil.toBean(result3, Result.class);
//        List data = result.getData();
//        List<ProProcessRoute> data2 = new ArrayList<>();
//        for (int i = 0; i < data.size(); i++) {
//            JSONObject jsonObject = (JSONObject) data.get(i);
//            ProProcessRoute bean = jsonObject.toBean(ProProcessRoute.class);
//            data2.add(bean);
//        }
//        List<PPRListVo> res = new ArrayList<>();
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<PPRListVo> res = scheduleMapper.proProcessRoute(dto);
        PageInfo<List<PPRListVo>> pageInfo = new PageInfo(res);
        List<String> params = new ArrayList<>();
        // 把拿出来的数据复制到 PPRListVo
        for (PPRListVo t : res) {
            params.add(t.getProductId().trim() + "-" + t.getProcessId().trim() + "-" + t.getProcessNo().trim());
        }

        // 查询 品号-工艺-工序  一样的到Set
        List<PPRVo> set = mapper.getList(params);
        Map<String, List<PPRresourceVo>> map = new HashMap<>();
        for (PPRVo p : set) {
            List<PPRresourceVo> list = map.get(p.getProductId() + "-" + p.getProcessId() + "-" + p.getProcessNo());
            if(list == null) {
                list = new ArrayList<>();
            }
            PPRresourceVo t = new PPRresourceVo();
            BeanUtils.copyPropertiesIgnoreCase(p, t);
            list.add(t);
            map.put(p.getProductId() + "-" + p.getProcessId() + "-" + p.getProcessNo(), list);
        }
        for (PPRListVo vo : res) {
//            String processName = vo.getProcessName();
            List<PPRresourceVo> vos = map.get(vo.getProductId().trim() + "-" + vo.getProcessId().trim() + "-" + vo.getProcessNo().trim());
            if (vos == null) continue;
            vo.setResourceGroups(vos);
//            vo.setProcessName(processName);
        }
        return Result.success(pageInfo);
    }

    @ApiOperation("根据产品工序工艺查询")
    @PostMapping("selPPRList")
    public Result<List<Productprocessresource>> selPPRList(@RequestBody PPRDto dto) {
        List<Productprocessresource> list = service.selPPRList(dto);
        return Result.success(list);
    }

    @Log("品号工序资源表 添加")
    @ApiOperation("品号工序资源表 添加")
    @PostMapping("addPPR")
    public Result addPPR(@RequestBody Productprocessresource dto) {
        if(StringUtils.isEmpty(dto.getProductId())
                || StringUtils.isEmpty(dto.getProcessId())
                || StringUtils.isEmpty(dto.getProcessNo()))  {
            return Result.error("品号或工艺ID或工序号为空");
        }
        if(dto.getResourceGroupId() == null
            || dto.getResourceTypeId() == null)  {
            return Result.error("资源类别或资源组为空");
        }
        if(StringUtils.isEmpty(dto.getMachiningCenter()))  {
            return Result.error("工作中心为空");
        }
        Resourcegroup resourcegroup = resourcegroupService.getById(dto.getResourceGroupId());
        if(resourcegroup == null) {
            return Result.error("资源组ID不存在");
        }
        Resourcegroup resourcetype = resourcegroupService.getById(dto.getResourceTypeId());
        if(resourcetype == null) {
            return Result.error("资源类别ID不存在");
        }
        // 校验该资源组是否属于该资源类别
        List<Resourcegroup> list = resourcegroupService.list();
        Map<Integer, Resourcegroup> posMap = new HashMap<>();
        for(Resourcegroup t : list) {
            posMap.put(t.getResourceGroupId(), t);
        }
        Integer originIdById = resourcegroupService.getOriginIdById(dto.getResourceGroupId(), posMap);
//        System.out.println(originIdById + "--" + dto.getResourceTypeId());
        if(originIdById != dto.getResourceTypeId()) {
            return Result.error("该资源组不属于该资源类别");
        }
        int count = service.count(new LambdaQueryWrapper<Productprocessresource>()
                .eq(Productprocessresource::getProductId, dto.getProductId())
                .eq(Productprocessresource::getProcessId, dto.getProcessId())
                .eq(Productprocessresource::getResourceGroupId, dto.getResourceGroupId())
                .eq(Productprocessresource::getResourceTypeId, dto.getResourceTypeId()));
        if(count > 0)  {
            return Result.error("已有一条品号，工序，资源类别，资源组相同的数据");
        }
        dto.setId(null);
        // 查看一下里面有没有主要码被用掉过，没有的话，就自动绑定进去。

        boolean b = service.save(dto);
        if(b) return Result.success("添加成功");
        return Result.error("添加失败");
    }

    @Log("品号工序资源表 删除")
    @DSTransactional
    @ApiOperation("删除")
    @PostMapping("delPPR")
    public Result delPPR(@RequestBody Integer id) {
        if(id == null || id == 0) {
            return Result.error("ID不能为空");
        }
        boolean b = service.removeById(id);
        if(!b) Result.error("删除失败");
        return Result.success("删除成功");
    }

    @Log("品号工序资源表 修改")
    @DSTransactional
    @ApiOperation("品号工序资源表 修改")
    @PostMapping("editPPR")
    public Result editPPR(@RequestBody Productprocessresource dto) {
        if(dto.getId() == null) {
            return Result.error("ID为空");
        }
        if(StringUtils.isEmpty(dto.getProductId())
                || StringUtils.isEmpty(dto.getProcessId())
                || StringUtils.isEmpty(dto.getProcessNo()))  {
            return Result.error("品号或工艺ID或工序号为空");
        }
        if(dto.getResourceGroupId() == null || dto.getResourceTypeId() == null) {
            return Result.error("资源类别或资源组为空");
        }
        if(StringUtils.isEmpty(dto.getMachiningCenter()))  {
            return Result.error("工作中心为空");
        }
        if(dto.getResourceGroupId() != null) {
            Resourcegroup resourcegroup = resourcegroupService.getById(dto.getResourceGroupId());
            if(resourcegroup == null) {
                return Result.error("资源组ID不存在");
            }
        }
        if(dto.getResourceTypeId() != null) {
            Resourcegroup resourcegroup = resourcegroupService.getById(dto.getResourceTypeId());
            if(resourcegroup == null) {
                return Result.error("资源类别ID不存在");
            }
        }
        // 校验该资源组是否属于该资源类别
        List<Resourcegroup> list = resourcegroupService.list();
        Map<Integer, Resourcegroup> posMap = new HashMap<>();
        for(Resourcegroup t : list) {
            posMap.put(t.getResourceGroupId(), t);
        }
        Integer originIdById = resourcegroupService.getOriginIdById(dto.getResourceGroupId(), posMap);
//        System.out.println(originIdById + "--" + dto.getResourceTypeId());
        if(originIdById != dto.getResourceTypeId()) {
            return Result.error("该资源组不属于该资源类别");
        }
        Productprocessresource one = service.getOne(new LambdaQueryWrapper<Productprocessresource>()
                .eq(Productprocessresource::getProductId, dto.getProductId())
                .eq(Productprocessresource::getProcessId, dto.getProcessId())
                .eq(Productprocessresource::getProcessNo, dto.getProcessNo())
                .eq(Productprocessresource::getResourceTypeId, dto.getResourceTypeId())
                .eq(Productprocessresource::getResourceGroupId, dto.getResourceGroupId()));
        if(one != null && !one.getId().equals(dto.getId())) {
            return Result.error("已有资源类别,资源组相同的行存在");
        }
//        System.out.println(dto);
        if(dto.getId() != null) {
            service.updateById(dto);
        }else{
            service.save(dto);
        }
        return Result.success("修改成功");
    }

    @ApiOperation("根据产品工序工艺查询可选的末级生产线/设备")
    @PostMapping("getProductLineMachine/{productId}/{processNo}/{processId}")
    public Result<List<Productprocessresource>> getProductLineMachine(@PathVariable String productId, @PathVariable String processNo, @PathVariable String processId) {
        List<Productprocessresource> list = mapper.getProductLineMachine(productId, processNo, processId);
        return Result.success(list);
    }

    @ApiOperation("根据资源类别查看品号能选的统驭")
    @PostMapping("getTYByProductId/{productId}/{processNo}/{processId}/{resourceTypeId}")
    public Result<List<Productprocessresource>> getTYByProductId(@PathVariable String productId, @PathVariable String processNo,
                                                                 @PathVariable String processId, @PathVariable Integer resourceTypeId) {
        List<Productprocessresource> list = mapper.getTYByProductId(productId, processNo, processId, resourceTypeId);
        return Result.success(list);
    }

    @ApiOperation("根据产品工序工艺查询可选的末级生产线/设备(宏竹版)")
    @PostMapping("getProductLineMachineHzView")
    public Result<List<GetProductLineMachineHzViewVo>> getProductLineMachineHzView(@RequestBody GetProductLineMachineHzViewDto dto) {
        List<GetProductLineMachineHzViewVo> list = mapper.getProductLineMachineHzView(dto);
        for(GetProductLineMachineHzViewVo item : list) {
            if(StringUtils.isNotEmpty(item.getMoctyudf05())) {
                // 查看目前已报工数量
//                BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(item.getMoctyudf05(), );
//                item.setBgNums(bgNums);
                Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, item.getMoctyudf05()));
                if(mocty != null) {
                    MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, mocty.getTy001())
                            .eq(MOCTA::getTA002, mocty.getTy002()));
                    item.setProductionNums(mocta.getTA017());
                }
            }
        }
        return Result.success(list);
    }

    @ApiOperation("根据资源类别查看品号能选的统驭(宏竹版)")
    @PostMapping("getTYByProductIdHzView")
    public Result<List<Productprocessresource>> getTYByProductIdHzView(@RequestBody GetTYByProductIdHzViewDto dto) {
        List<Productprocessresource> list = mapper.getTYByProductIdHzView(dto);
        return Result.success(list);
    }

//    @Log("品号工序资源表 列表")
//    @ApiOperation("品号工序资源表 列表")
//    @PostMapping("PPRList")
//    public Result<PageInfo<List<PPRVo>>> PPRList(@RequestBody PPRListDto dto) {
//        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
//        List<PPRVo> list = service.PPRList(dto);
//        PageInfo<List<PPRVo>> pageInfo = new PageInfo(list);
//        return Result.success(pageInfo);
//    }

}
